import 'package:flutter_enjoy_plus_seven/constants/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TokenManager {
  String? _token; // 访问token
  String? _refreshToken; // 刷新token(用于续期访问token)

  init() async {
    final prefs = await _getInstance();
    _token = prefs.getString(GlobalVariable.TOKEN);
    _refreshToken = prefs.getString(GlobalVariable.REFRESH_TOKEN);
  }

  Future<SharedPreferences> _getInstance() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs;
  }

  /// 存token
  setToken(String token, String refreshToken) async {
    final prefs = await _getInstance();
    prefs.setString(GlobalVariable.TOKEN, token); // 持久化
    _token = token; // 内存中保存一份
    if (refreshToken.isNotEmpty) {
      prefs.setString(GlobalVariable.REFRESH_TOKEN, refreshToken);
      _refreshToken = refreshToken;
    }
  }

  /// 取token
  String getToken() {
    return _token ?? '';
  }

  /// 取刷新token
  String getRefreshToken() {
    return _refreshToken ?? '';
  }

  /// 删token
  deleteToken() async {
    final prefs = await _getInstance();
    // 删除token
    prefs.remove(GlobalVariable.TOKEN);
    _token = null;
    // 删除刷新token
    prefs.remove(GlobalVariable.REFRESH_TOKEN);
    _refreshToken = null;
  }
}

final tokenManager = TokenManager();
